<template>
  <div>
    <el-card style="margin: 20px 0">
      <CategorySelect :show="!isShowTable" @getCategoryId="getCategoryId" />
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!cate3Id"
          @click="toAddAttr"
        >添加属性</el-button>
        <el-table border style="width: 100%; margin-top: 10px" :data="attrList">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="attrName" label="属性名称" width="150" align="center" />
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                type="success"
                style="margin-right: 15px"
              >{{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150" align="center">
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="toUpdateAttr(row)"
              />
              <el-button type="danger" icon="el-icon-delete" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性|修改属性 -->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrInfo.attrName"
          @click="addAttrValue"
        >添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table
          style="width: 100%; margin: 20px 0"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="prop" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                v-if="row.isEdit"
                :ref="$index"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                @blur="toView(row)"
                @keyup.native.enter="toView(row)"
              />
              <span v-else style="display: block" @click="toEdit(row, $index)">{{
                row.valueName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <!-- 注意此处事件：@onConfirm 是 ElementUI 2.13.2 版本的名字，新版本为 @confirm -->
              <el-popconfirm
                :title="`确定删除${row.valueName}吗？`"
                @onConfirm="deleteAttrValue($index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="attrInfo.attrValueList.length < 1"
          @click="addOrUpdateAttr"
        >保存</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      cate1Id: '',
      cate2Id: '',
      cate3Id: '',
      // 平台属性数据
      attrList: [],
      // 控制table的显示与隐藏
      isShowTable: true,
      // 新增属性|修改属性 的属性信息
      attrInfo: {
        // 属性名
        attrName: '',
        // 属性值列表
        attrValueList: [],
        // 三级分类id
        categoryId: 0,
        categoryLevel: 3
      }
    }
  },
  methods: {
    // 自定义事件回调
    getCategoryId({ categoryId, level }) {
      if (level == 1) {
        this.cate2Id = ''
        this.cate3Id = ''
        this.cate1Id = categoryId
      } else if (level == 2) {
        this.cate3Id = ''
        this.cate2Id = categoryId
      } else {
        this.cate3Id = categoryId
        // 发请求获取平台属性
        this.getAttrList()
      }
    },
    // 获取平台属性
    async getAttrList() {
      const { cate1Id, cate2Id, cate3Id } = this
      const result = await this.$API.attr.reqAttrList(cate1Id, cate2Id, cate3Id)
      if (result.code == 200) {
        this.attrList = result.data
      }
    },
    // 添加属性按钮的回调
    toAddAttr() {
      this.isShowTable = false
      this.attrInfo = {
        // 属性名
        attrName: '',
        // 属性值列表
        attrValueList: [],
        // 三级分类id
        categoryId: this.cate3Id,
        categoryLevel: 3
      }
    },
    // 修改属性按钮的回调
    toUpdateAttr(row) {
      this.isShowTable = false
      // 需要用到深拷贝
      this.attrInfo = cloneDeep(row)
      this.attrInfo.attrValueList.forEach((item) => {
        // item.isEdit = false
        /**
         * 上面这种写法虽说可以加上`isEdit`字段，但是视图不会跟着变化(isEdit不是【响应式】的)
         * 所以必须采用 $set 添加响应式数据
         *
         * vm.$set( target, propertyName/index, value )
           {Object | Array} target
					 {string | number} propertyName/index
					 {any} value
         */
        this.$set(item, 'isEdit', false)
      })
    },
    // 添加属性值按钮的回调-----增加属性值的input框数量
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: '',
        isEdit: true
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    // 查看模式【失去焦点】
    toView(row) {
      // 输入的属性值不能为空
      if (row.valueName.trim() == '') {
        this.$message({
          message: '属性值不能为空！',
          type: 'warning'
        })
        return
      }
      // 新增的属性值不能与已有的重复
      const isRepeat = this.attrInfo.attrValueList.some((item) => {
        // row是新增的属性值
        if (row !== item) {
          return row.valueName.trim() == item.valueName
        }
      })
      if (isRepeat) {
        this.$message({
          message: '属性值不能重复！',
          type: 'warning'
        })
        return
      }
      row.isEdit = false
    },
    // 编辑模式【获取焦点】
    toEdit(row, index) {
      row.isEdit = true
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 气泡提示框的确认按钮
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1)
    },
    // 保存按钮：添加|修改属性
    async addOrUpdateAttr() {
      // 整理参数
      // 若属性值为空，不能提交给服务器，还需要删除属性值不为空的元素的`isEdit`字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item) => {
        if (item.valueName != '') {
          // 删除flag属性
          delete item.isEdit
          return true
        }
      })
      try {
        await this.$API.attr.reqAddOrUpdateAttr(this.attrInfo)
        this.isShowTable = true
        this.$message({
          message: '保存成功！',
          type: 'success'
        })
        this.getAttrList()
      } catch (error) {
        this.$message({
          message: '保存失败！',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style></style>
